package com.cn.shiro.zy.shiro.config;

import com.cn.shiro.zy.shiro.entity.User;
import com.cn.shiro.zy.shiro.utils.MD5Util;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangyi
 * @date 2018/12/12 20:43
 */
public class MyHashedCredent extends HashedCredentialsMatcher implements Serializable {
    public MyHashedCredent(){}
    /**
     * 以后放到redis中保存
     */
    private Cache<String, AtomicInteger> passwordRetryCache;

    public MyHashedCredent(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        //限制每个用户的请求登录次数（密码错误的时候）
        String username = (String) token.getPrincipal();
        if(!Objects.isNull(passwordRetryCache)) {
            // retry count + 1
            AtomicInteger retryCount = passwordRetryCache.get(username);
            if (retryCount == null) {
                retryCount = new AtomicInteger(0);
                passwordRetryCache.put(username, retryCount);
            }
            if (retryCount.incrementAndGet() > 5) {
                // if retry count > 5 throw
                throw new ExcessiveAttemptsException();
            }
        }
        boolean matches = super.doCredentialsMatch(token, info);
        if (matches) {
            // clear retry count
//            passwordRetryCache.remove(username);
        }
        return matches;
    }
}
